<template>
  <div>
    <a-upload v-if="!disabled" :show-upload-list="false" :multiple="true" :before-upload="beforeUpload" @change="customRequest">
      <a-button v-bind="btnAttrs" type="primary" class="mb20"  @click="fileInfo = []">
        <a-icon type="upload" />
        {{ btnName }}
      </a-button>
    </a-upload>
    <a-table bordered rowKey="fileId" :columns="columns" :data-source="value" :loading="loading">
      <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
      <span slot="action" slot-scope="text, record">
        <div class="pub-table-list-action">
          <span v-if="!checkVisibleInDetail">
            <a href="javascript:" @click="$noticeWarning('抱歉，app端无法导出，请在系统电脑端进行导出')">导出</a>
          </span>
          <template v-else>
            <span v-if="record.fileInfoVO">
              <a :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + record.fileInfoVO.fileId" target="_parent">导出</a>
            </span>
            <span v-if="record.fileInfoVO" target="_blank" @click="$filePreview(record.fileInfoVO)">预览</span>
          </template>
          <span v-if="!disabled && record.keyProgram == '-'" @click="deleteFile(record.fileInfoVO)">删除</span>
        </div>
      </span>
    </a-table>
  </div>
</template>
<script>
import { deleteFile, uploadFile } from '@/api'
import Vue from 'vue'
import PreView from '@/components/PreView'
import { checkVisibleInDetail } from '@/utils/util'
import { isChinese } from '@/utils/regExpression'
import { colspan, colspanProjectName } from '../model.js'
import debounce from 'lodash/debounce'
export default {
  props: {
    // 业务编码
    businessCode: {
      type: String,
      required: true
    },
    // 是否禁止上传
    disabled: {
      type: Boolean,
      default() {
        return false
      }
    },
    value: {
      type: [Array, Object],
      default() {
        return []
      }
    },
    // 按钮名称
    btnName: {
      type: String,
      default: () => '上传'
    },
    // 按钮属性
    btnAttrs: {
      type: [Object],
      default() {
        return null
      }
    }
  },
  data() {
    return {
      checkVisibleInDetail: checkVisibleInDetail(this),
      token: Vue.getAcloudProvider().getAccessToken(),
      loading: false,
      tableData: [],
      fileInfo: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'serial',
          width: 70,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '项目名称',
          dataIndex: 'name',
          width: '350px',
          ellipsis: true
        },
        {
          title: '是否重点项目',
          dataIndex: 'keyProgram'
        },
        {
          title: '附件名称',
          dataIndex: 'fileName',
          customRender() {
            return arguments[1].fileInfoVO?.fileName
          }
        },
        {
          title: '附件类型',
          dataIndex: 'suffixName',
          customRender: (text, row, index) => {
            return row.fileInfoVO?.suffixName
          }
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 150,
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },

  mounted() {
    //初始化表头
    this.initColumns()
  },
  methods: {
    initColumns() {
      this.columns[1].customRender = (text, row, index) => {
        return colspan(text, row, index, this.value, 'name')
      }
      this.columns[2].customRender = (text, row, index) => {
        return colspanProjectName(text, row, index, this.value, 'name')
      }
    },
    beforeUpload(info) {
      return false
    },
    /**
     * @description: 提示防抖
     * @param {void}
     * @return {function}
     */
    numMesgDebounce: debounce(function () {
      this.$message.error(`一次最多上传10个文件！`)
      this.fileInfo = this.fileInfo.slice(0, 10)
    }, 500),
    customRequest(date) {
      // let file = date.file.originFileObj
      //校验是否包含中文
      let re = new RegExp('[\u4E00-\\u9FFF]+', 'g')
      let pass = re.test(date.file.name)
      if (!pass) {
        this.$message.warning('请规范附件名称，附件名称中需含有汉字')
        return false
      }
      this.fileInfo.push(date.file)
      if (this.fileInfo.length > 10) {
        this.numMesgDebounce()
        return
      }
      this.fileChange()
    },
    /**
     * @description: 文件上传防抖
     * @param {function}
     * @return {void}
     */
    fileChange: debounce(function () {
      this.uploadFnChange()
    }, 500),
    /**
     * @description: 文件上传前置条件
     * @param {function}
     * @return {void}
     */
    async uploadFnChange() {
      for (let index = 0; index < this.fileInfo.length; index++) {
        await this.uploadFn(this.fileInfo[index])
      }
    },
    //文件上传
    async uploadFn(file) {
      const fb = new FormData()
      fb.append('file', file)
      fb.append('businessCode', this.businessCode)
      this.loading = true
      let res = await uploadFile(fb).catch((err) => (this.loading = false))
      if (res.code === 200) {
        let temp = this.$clone(this.value)
        temp.push({ name: '-', keyProgram: '-', branchCompanyName: '-', fileInfoVO: res.data })
        this.$emit('input', temp)
      }
      this.loading = false
    },
    async deleteFile(record) {
      console.log('record',record)
      this.$submitConfirm(async () => {
        let commonId = record.originFileObj && record.originFileObj.commonId ? record.originFileObj.commonId : record.commonId
        this.loading = true
        let res = await deleteFile([commonId])
        if (res.data.code === this.SUCCESS_CODE) {
          let temp = this.$clone(this.value)
          let resIndex = temp.findIndex((v) => v?.fileInfoVO.id === record.id)
          if (resIndex !== -1) {
            temp.splice(resIndex, 1)
            this.$emit('input', temp)
          }
        }
        this.loading = false
      }, '确定删除此文件？')
    }
  }
}
</script>
